﻿package emusic.api.feeds 
{
	import emusic.api.adapters.SummaryAdapter;
	import emusic.api.data.SummaryData;
	/**
	 * ...
	 * @author Martin Legris ( http://blog.martinlegris.com )
	 */
	public class SummaryDataFeed
	{
		
		protected var _xml:XML;
		protected var _pointer:Number = 0;
		protected var _nodeName:String = "data";
		
		public function SummaryDataFeed(xml:XML, nodeName:String) 
		{
			_xml = xml;
			_pointer = 0;
			
			if (nodeName != null)
				_nodeName = nodeName;
			else
				throw new Error("You must specify a nodeName");
		}
		
		public function get count():Number
		{
			return _xml.child(_nodeName).length();
		}
		
		public function getAt(idx:Number):SummaryData
		{
			if (idx >= 0 && idx < count)			
				return SummaryAdapter.digestSummary(_xml.child(_nodeName)[idx]);
			else
				return null;
		}
		
		public function first():SummaryData
		{
			return getAt(_pointer = 0);
		}
		
		public function next():SummaryData
		{
			if (_pointer < count)
				return getAt(_pointer++);
			else
			{
				_pointer = 0;
				return null;
			}
		}
		
		public function toArray():Array
		{
			var result:Array = [];
			var lastPointer:Number = _pointer;
			first();
			var data:SummaryData;
			while (data = next())
				result.push(data);
				
			_pointer = lastPointer;
			
			return result;
		}
	}
}